<script setup lang="ts">

import {ref, onMounted} from 'vue'
import { Search,ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ElTable } from 'element-plus'
import { ElButton, ElDialog } from 'element-plus'
import router from '@/router'
import { GetUser } from "@/utils/lStorage"

import {formatCreateTime ,getTime} from "@/utils/format"
import {apiTaskList,apiTaskCreate,apiTaskDelete, apiGroupList} from '@/api/api'


const searchKey = ref({
  DeviceGroupId:"",
  DeviceGroupName:"",
  Name:"",
  Desc:"",
  Status:"",
})
const pageConfig = ref({
  pageNum : 1,
  pageSize :15,
  total:0,

})


const groupList = ref([])
async function handlerGroupList(){
  const req = {
    pageSize:100,
  } 
 const data = await apiGroupList(req)
  if (data.CODE != "ok") {
      console.log(data)
      ElMessage.error("执行失败， 请联系管理员")
      return 
  }
  groupList.value = data.DATA.DeviceGroupList

}





const taskList = ref([])

async function handlerTaskList() {
  const req = {
    pageNum:pageConfig.value.pageNum,
    pageSize:pageConfig.value.pageSize,
  }
  if  (searchKey.value.DeviceGroupId){
    req.DeviceGroupId = searchKey.value.DeviceGroupId
  }
  if  (searchKey.value.DeviceGroupName){
    req.DeviceGroupName = searchKey.value.DeviceGroupName
  }
  if  (searchKey.value.Name){
    req.Name = searchKey.value.Name
  }
  if  (searchKey.value.Desc){
    req.Desc = searchKey.value.Desc
  }
  if  (searchKey.value.Status){
    req.Status = searchKey.value.Status
  }

  const data = await apiTaskList(req)
  if (data.CODE != "ok") {
      console.log(data)
      ElMessage.error("执行失败， 请联系管理员")
      return 
  }

  pageConfig.value.pageNum = data.DATA.PageNumber
  pageConfig.value.pageCount = data.DATA.PageCount
  pageConfig.value.pageSize = data.DATA.PageSize
  pageConfig.value.total = data.DATA.TotalCount
  taskList.value = data.DATA.TaskList
}

const handlerTaskDownload = (item)=>{
  const url = "/gaoqian/api/?&api_action=Attachment.Download&AttPath=" + item.ProductPath
  window.open(url)
}


const paramCreate =ref({
  openFlag: false ,
  DeviceGroupName:"",
})


function handlerAttUploadSuccess(resp) {
  if (resp.CODE != "ok") {
    console.log(resp)
    ElMessage.error("执行失败， 请联系管理员")
    return 
  }
  paramCreate.value.ProductPath = resp.DATA.AttachmeentId
}

const beforeAvatarUpload = (file) =>{
  if (file.type != "application/wps-office.xlsx") {
    ElMessage.error('请选择 excel 文件')
    return false 
  }
  const cTime =  getTime()
  if (!paramCreate.value.Name) {
    paramCreate.value.Name = cTime  + file.name
  }
  if (!paramCreate.value.Desc) {
    paramCreate.value.Desc = cTime + file.name
  }

  return true
}



async function handlerTaskCreate () {
  // upload file 
  if  (!paramCreate.value.DeviceGroupId){
      ElMessage.error('执行分组未选择， 请选择执行分组')
      return
  }

  if  (!paramCreate.value.ProductPath){
      ElMessage.error('请选择需商品文件')
      return
    }

  const data = await apiTaskCreate(paramCreate.value)
  if (data.CODE != "ok") {
      console.log(data)
      ElMessage.error("执行失败， 请联系管理员")
      return 
  }

  ElMessage({
    message: '创建成功',
    type: 'success',
  })

  handlerTaskList()
  paramCreate.value = {}
  return 
}

// async function handlerGroupCreate() {
//   if (!paramCreate.value.DeviceGroupName){
//       ElMessage.error("请输入分组名称")
//       return 
//   }

// }


const handleTaskDetail = (item) => {
  router.push({ path: '/task/detail', query: { "id": item.TaskId } })
}

async function handlerTaskDelete(item)  {
 
  const req= {
    TaskId: item.TaskId,
  }
  const data = await  apiTaskDelete(req)
  if (data.CODE != "ok") {
      console.log(data)
      ElMessage.error("执行失败， 请联系管理员")
      return 
  }

    ElMessage({
      message: '操作成功！',
      type: 'success',
    })
  handlerTaskList()
    
}



onMounted(() => {
  handlerGroupList()
  handlerTaskList()
})

</script>

<template>
  <el-row :gutter="20" justify="space-between" >
    <el-col :span="8">
      <el-button type="primary" @click="paramCreate.openFlag=true" >导入</el-button>
    </el-col>
    <el-col :span="16">
      <el-row justify="end" :gutter="10">
        <el-col  :span="4"> 
            <el-select v-model="searchKey.DeviceGroupId"  placeholder="分组" clearable >
            <el-option
              v-for="status in groupList"
              :key="status.DeviceGroupId"
              :label="status.DeviceGroupName"
              :value="status.DeviceGroupId"
            />
          </el-select>
        </el-col>
        <el-col  :span="4"> 
            <el-input v-model="searchKey.Name" placeholder="名称" clearable />
        </el-col>
        <el-col  :span="4"> 
            <el-input v-model="searchKey.Code" placeholder="代号" clearable />
        </el-col>
        <el-col :span="2"> 
          <el-button   class='pagination' type="primary" :icon="Search" @click="handlerDeviceList" >查询</el-button>
        </el-col>
      </el-row>
    </el-col>

  </el-row>

<div class="info_box">
  <el-table :data="taskList" style="width: 100%">
    <el-table-column prop="Name" label="任务名称" />
    <el-table-column prop="DeviceGroupName" label="执行分组" width="300" />
    <el-table-column prop="ProductPath" label="文件名"  />
    <el-table-column prop="Desc" label="说明"  />
    <el-table-column prop="CreateTime" label="创建时间" :formatter="formatCreateTime" width="180" />
        <el-table-column label="操作" width="250" >
        <template  #default="item">
          <el-button link type="primary" @click="handlerTaskDownload(item.row)"  >下载商品</el-button>
          <el-button link type="primary" @click="handleTaskDetail(item.row)">详情</el-button>
          <el-button link type="danger" @click="handlerTaskDelete(item.row)"  >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <el-pagination class='pagination' size="large" :page-size="pageConfig.pageSize" layout=" prev, pager, next, total" :total="pageConfig.total"
      v-model:current-page="pageConfig.pageNum" @current-change="handlerSkillList" />

</div>


<el-dialog v-model="paramCreate.openFlag" title="添加" :with-header="false">
  <div class="info_box">
    
  <el-form :model="paramCreate" label-width="120px">

    <el-form-item label="执行分组">
      <el-select v-model="paramCreate.DeviceGroupId"  placeholder="分组" clearable >
        <el-option
              v-for="status in groupList"
              :key="status.DeviceGroupId"
              :label="status.DeviceGroupName"
              :value="status.DeviceGroupId"
            />
        </el-select>
    </el-form-item>
    
    <el-form-item label="商品列表">
      <div class="box_upload" >
        <el-upload
        ref="uploadRef"
        :multiple:="false"
        :auto-upload="true"
        action="/gaoqian/api/?api_action=Attachment.Upload"  
        :on-success="handlerAttUploadSuccess"
        :before-upload="beforeAvatarUpload"
        >
        <template #trigger>
          <el-button type="primary">选择商品文件</el-button>
        </template>
      </el-upload>
    </div>
    </el-form-item>    

    <el-form-item label="任务名称">
      <el-input v-model="paramCreate.Name" clearable/>
    </el-form-item>

  <el-form-item label="任务说明">
      <el-input v-model="paramCreate.Desc"     
        autosize
        clearable
      type="textarea"
      placeholder="配置说明"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handlerTaskCreate">提交</el-button>
      <el-button @click="paramCreate.openFlag=false">取消</el-button>
    </el-form-item>
   </el-form>
  </div>

  </el-dialog>


</template>

<style scoped>

.pagination {
  float: right;
}

.right_button{
  float: right;
}
.box_create{
/*   padding: 3em; */
  width: 300px;
}

</style>